#include "PluginXmlFunction.h"
#include "DefineCommon.h"
#include "EItem.h"
#include <sstream>
#include <fstream>
#include <ostream>
#include <istream>
#include <QFile>
#include <EXmlNode.h>
#include <EXmlRoot.h>

EItemPtr PluginXmlFunction::convertXmlFileToEItem(const QString& fileName)
{
    EXmlRootPtr itemRoot = NewSmartPtr(EXmlRoot)();
    
    itemRoot->ui_XmlPath = fileName.toStdString().data();
    itemRoot->setName("xml file");

    QDomDocument doc("xmlDoc");
    QFile file(fileName);
    if(!file.open(QIODevice::ReadOnly))
    {
        ELOG_ERROR("open file failed, fileName=%s", fileName.toLocal8Bit().data());
        return itemRoot;
    }

    if(!doc.setContent(&file))
    {
        ELOG_ERROR("QDomDocuemnt setContent failed, fileName=%s", fileName.toLocal8Bit().data());
        file.close();
        return itemRoot;
    }
    file.close();

    QDomElement docElem = doc.documentElement();
    convertXmlNodeToItem(docElem, itemRoot);

    return itemRoot;
}

void PluginXmlFunction::convertXmlNodeToItem(QDomElement& docElem, EXmlNodePtr itemParent)
{
    //new item and add to tree
    EXmlNodePtr itemTemp = NewSmartPtr(EXmlNode)();
    //if attribute "Name-String" exits, than add it to tag name, this is to fit CAA's output
    if (docElem.hasAttribute("Name-String"))
    {
        QString tempStr = docElem.tagName() +"-" + docElem.attribute("Name-String");
        itemTemp->setName(tempStr.toStdString().data());
    }
    else
    {
        itemTemp->setName(docElem.tagName().toStdString().data());
    }
    itemParent->addChild(itemTemp);
    
    //fill property
    for (int i = 0; i < docElem.attributes().count(); i++)
    {
        QDomAttr tempAttr = docElem.attributes().item(i).toAttr();
        itemTemp->getOrCreatMeta()->addProperty(
            tempAttr.name().toStdString().data(),
            tempAttr.value().toStdString().data());
    }

    QDomNode n = docElem.firstChild();
    while(!n.isNull())
    {
        QDomElement e = n.toElement();
        if(e.isNull() == false)
        {
            // ELOG_INFO("%s", e.tagName().toStdString().data());
            convertXmlNodeToItem(e,itemTemp);
        }

        n = n.nextSibling();
    }
}
